<template>
  <view class="bind-settle-container">
    <view class="bind-header">
      <text class="bind-title">绑定结算方式</text>
      <view class="close-btn" @click="handleClose">×</view>
    </view>
    
    <view class="bind-info">
      <text class="bind-label">赛程模式: {{ scheduleModelId }}</text>
    </view>
    
    <view class="bind-section">
      <view class="section-header">
        <text class="section-title">已绑定的结算方式</text>
        <view class="add-btn" @click="openAddSettlePicker">添加结算方式</view>
      </view>
      
      <view v-if="settleBindLoading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="settleBindList.length === 0" class="empty-state">
        <text>暂未绑定结算方式</text>
      </view>
      
      <view v-else class="bind-list">
        <view 
          class="bind-item" 
          v-for="bind in settleBindList" 
          :key="bind.id"
        >
          <view class="bind-content">
            <text class="settle-id">结算方式: {{ bind.matchScheduleSettleId }}</text>
            <text class="settle-type">结算类型: {{ getSettleTypeText(bind.settleType) }}</text>
            <text class="bind-time">绑定时间: {{ formatDate(bind.createTime) }}</text>
          </view>
          <view class="unbind-btn" @click="openUnbindSettlePicker(bind)">解绑</view>
        </view>
      </view>
    </view>
    
    <!-- 添加结算方式选择器 -->
    <PopuleView
      v-model="showAddSettlePicker"
      title="添加结算方式"
      :list-data="settleListForPicker"
      :show-submit="true"
      submit-text="绑定"
      item-label="label"
      item-key="id"
      :selected-value="selectedSettleId"
      @submit="handleBindSettle"
      @item-click="(item) => selectedSettleId = item.id"
    />
    
    <!-- 解绑确认弹窗 -->
    <PopuleView
      v-model="showUnbindConfirm"
      title="确认解绑"
      :description="unbindConfirmText"
      :show-submit="true"
      submit-text="确认解绑"
      @submit="handleUnbindSettle"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { MatchScheduleSettleAPI, MatchScheduleModelSettleRefAPI } from '@/api/battle.js'
import PopuleView from "@/components/UiView/PopuleView.vue";

const props = defineProps({
  scheduleModelId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['close'])

// 响应式数据
const settleBindLoading = ref(false)
const settleLoading = ref(false)
const settleBinding = ref(false)
const settleBindList = ref([])
const settleList = ref([])
const selectedSettleId = ref('')
const showAddSettlePicker = ref(false)
const showUnbindConfirm = ref(false)
const currentUnbindItem = ref(null)

// 结算类型选项
const settleTypeOptions = ['普通结算', '积分结算', '排名结算', '自定义结算']

// 获取结算类型文本
const getSettleTypeText = (type) => {
  return settleTypeOptions[type] || '未知'
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未知'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 解绑确认文本
const unbindConfirmText = computed(() => {
  if (currentUnbindItem.value) {
    return `确定要解绑结算方式 ${currentUnbindItem.value.matchScheduleSettleId} 吗？`
  }
  return '确定要解绑吗？'
})

// 结算列表用于选择器
const settleListForPicker = computed(() => {
  return settleList.value.map(settle => ({
    id: settle.id,
    label: `ID: ${settle.id} | ${settle.settleName || '未命名'} | ${getSettleTypeText(settle.settleType)}`
  }))
})

// 加载结算方式绑定列表
const loadSettleBindList = async () => {
  if (!props.scheduleModelId) return
  
  settleBindLoading.value = true
  try {
    const result = await MatchScheduleModelSettleRefAPI.page({
      matchScheduleModelId: props.scheduleModelId,
      pageNum: 0,
      pageSize: 100
    })
    
    if (result.code === 0 && result.data) {
      settleBindList.value = result.data.list || result.data || []
    } else {
      settleBindList.value = []
      throw new Error(result.msg || '获取结算方式绑定列表失败')
    }
  } catch (error) {
    console.error('获取结算方式绑定列表失败:', error)
    uni.showToast({
      title: error.message || '获取结算方式绑定列表失败',
      icon: 'none'
    })
  } finally {
    settleBindLoading.value = false
  }
}

// 加载结算方式列表
const loadSettleList = async () => {
  settleLoading.value = true
  try {
    const result = await MatchScheduleSettleAPI.page({
      pageNum: 0,
      pageSize: 100
    })
    
    if (result.code === 0 && result.data) {
      settleList.value = result.data.list || result.data || []
    } else {
      settleList.value = []
      throw new Error(result.msg || '获取结算方式列表失败')
    }
  } catch (error) {
    console.error('获取结算方式列表失败:', error)
    uni.showToast({
      title: error.message || '获取结算方式列表失败',
      icon: 'none'
    })
  } finally {
    settleLoading.value = false
  }
}

// 打开添加结算方式选择器
const openAddSettlePicker = async () => {
  if (settleList.value.length === 0) {
    await loadSettleList()
  }
  selectedSettleId.value = ''
  showAddSettlePicker.value = true
}

// 绑定结算方式
const handleBindSettle = async () => {
  if (!selectedSettleId.value || !props.scheduleModelId) {
    uni.showToast({
      title: '请选择结算方式',
      icon: 'none'
    })
    return
  }
  
  // 检查是否已绑定
  const isBound = settleBindList.value.some(bind => bind.matchScheduleSettleId === selectedSettleId.value)
  if (isBound) {
    uni.showToast({
      title: '该结算方式已绑定',
      icon: 'none'
    })
    return
  }
  
  settleBinding.value = true
  try {
    const selectedSettle = settleList.value.find(settle => settle.id === selectedSettleId.value)
    if (!selectedSettle) {
      throw new Error('未找到选中的结算方式')
    }
    
    const result = await MatchScheduleModelSettleRefAPI.create({
      matchScheduleModelId: props.scheduleModelId,
      matchScheduleSettleId: selectedSettleId.value,
      settleType: selectedSettle.settleType || 0
    })
    
    if (result.code === 0) {
      uni.showToast({
        title: '绑定成功',
        icon: 'success'
      })
      showAddSettlePicker.value = false
      selectedSettleId.value = ''
      loadSettleBindList()
    } else {
      throw new Error(result.msg || '绑定失败')
    }
  } catch (error) {
    console.error('绑定结算方式失败:', error)
    uni.showToast({
      title: error.message || '绑定失败',
      icon: 'none'
    })
  } finally {
    settleBinding.value = false
  }
}

// 打开解绑确认弹窗
const openUnbindSettlePicker = (bind) => {
  currentUnbindItem.value = bind
  showUnbindConfirm.value = true
}

// 解绑结算方式
const handleUnbindSettle = async () => {
  if (!currentUnbindItem.value) return
  
  try {
    const result = await MatchScheduleModelSettleRefAPI.remove({
      matchScheduleModelSettleRefId: currentUnbindItem.value.id
    })
    
    if (result.code === 0) {
      uni.showToast({
        title: '解绑成功',
        icon: 'success'
      })
      showUnbindConfirm.value = false
      currentUnbindItem.value = null
      loadSettleBindList()
    } else {
      throw new Error(result.msg || '解绑失败')
    }
  } catch (error) {
    console.error('解绑结算方式失败:', error)
    uni.showToast({
      title: error.message || '解绑失败',
      icon: 'none'
    })
  }
}

// 关闭组件
const handleClose = () => {
  emit('close')
}

// 监听scheduleModelId变化
watch(() => props.scheduleModelId, (newId) => {
  if (newId) {
    loadSettleBindList()
  }
}, { immediate: true })

// 组件挂载时加载数据
onMounted(() => {
  if (props.scheduleModelId) {
    loadSettleBindList()
  }
})
</script>

<style lang="scss" scoped>
.bind-settle-container {
  background: #F0F0E4;
  border-radius: 10rpx;
  padding: 10rpx;
  margin: 10rpx 0;
}

.bind-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
  
  .bind-title {
    font-size: 16rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    width: 30rpx;
    height: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    color: #666;
    cursor: pointer;
  }
}

.bind-info {
  margin-bottom: 10rpx;
  
  .bind-label {
    font-size: 14rpx;
    color: #666;
  }
}

.bind-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;
    
    .section-title {
      font-size: 14rpx;
      color: #333;
      font-weight: bold;
    }
    
    .add-btn {
      font-size: 12rpx;
      color: #667eea;
      padding: 4rpx 8rpx;
      border: 1rpx solid #667eea;
      border-radius: 4rpx;
      cursor: pointer;
    }
  }
  
  .loading-container, .empty-state {
    text-align: center;
    padding: 20rpx;
    color: #999;
    font-size: 12rpx;
  }
  
  .bind-list {
    .bind-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8rpx;
      margin-bottom: 8rpx;
      background: #fff;
      border-radius: 6rpx;
      
      .bind-content {
        flex: 1;
        
        .settle-id {
          display: block;
          font-size: 12rpx;
          color: #333;
          margin-bottom: 4rpx;
        }
        
        .settle-type {
          display: block;
          font-size: 11rpx;
          color: #666;
          margin-bottom: 4rpx;
        }
        
        .bind-time {
          display: block;
          font-size: 11rpx;
          color: #999;
        }
      }
      
      .unbind-btn {
        font-size: 12rpx;
        color: #ff4757;
        padding: 4rpx 8rpx;
        border: 1rpx solid #ff4757;
        border-radius: 4rpx;
        cursor: pointer;
      }
    }
  }
}

.loading-spinner {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #f3f3f3;
  border-top: 2rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 10rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

